<script setup lang="ts">
import type { TableProps } from 'ant-design-vue';

import { computed, onMounted, reactive, ref } from 'vue';

import { Plus, Search, Trash2, UserRoundPen } from '@vben/icons';

import { message } from 'ant-design-vue';

import CategoryModal from './components/CategoryModal.vue';
import CombinationModal from './components/CombinationModal.vue';
import CommonItemModal from './components/CommonItemModal.vue';

// 响应式数据
const loading = ref(false);
const selectedScenario = ref('prescription');
const selectedCombinations = ref<string[]>([]);
const currentCombination = ref<any>(null);

// 模态框控制
const categoryModalVisible = ref(false);
const combinationModalVisible = ref(false);
const commonItemModalVisible = ref(false);

// 使用场景数据
const scenarios = ref([
  { id: 'prescription', name: '处方组合' },
  { id: 'examination', name: '检验组合' },
  { id: 'treatment', name: '处置组合' },
  { id: 'surgery', name: '手术组合' },
  { id: 'inpatient', name: '住院组合' },
  { id: 'grooming', name: '美容组合' },
  { id: 'vaccine', name: '疫苗组合' },
  { id: 'product', name: '商品组合' },
  { id: 'deworming', name: '驱虫组合' },
]);

// 组合数据
const combinations = ref([
  {
    id: '1',
    scenario: 'prescription',
    name: '感冒处方组合',
    specification: '标准组合',
    unit: '套',
    addedBy: '张医生',
    addTime: '2024-01-15 10:30:00',
    items: [
      { id: '1', name: '阿莫西林', quantity: 1, unit: '盒' },
      { id: '2', name: '维生素C', quantity: 1, unit: '瓶' },
    ],
  },
  {
    id: '2',
    scenario: 'prescription',
    name: '消炎处方组合',
    specification: '标准组合',
    unit: '套',
    addedBy: '李医生',
    addTime: '2024-01-14 15:20:00',
    items: [
      { id: '3', name: '头孢克肟', quantity: 1, unit: '盒' },
      { id: '4', name: '布洛芬', quantity: 1, unit: '盒' },
    ],
  },
]);

// 表格列定义
const columns: TableProps['columns'] = [
  {
    title: '编号',
    dataIndex: 'id',
    key: 'id',
    width: 80,
  },
  {
    title: '名称',
    dataIndex: 'name',
    key: 'name',
    width: 200,
  },
  {
    title: '规格',
    dataIndex: 'specification',
    key: 'specification',
    width: 120,
  },
  {
    title: '单位',
    dataIndex: 'unit',
    key: 'unit',
    width: 80,
  },
  {
    title: '添加人',
    dataIndex: 'addedBy',
    key: 'addedBy',
    width: 100,
  },
  {
    title: '添加时间',
    dataIndex: 'addTime',
    key: 'addTime',
    width: 150,
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right',
  },
];

// 计算属性
const filteredCombinations = computed(() => {
  return combinations.value.filter(
    (combination) => combination.scenario === selectedScenario.value,
  );
});

const isAllSelected = computed(() => {
  return (
    filteredCombinations.value.length > 0 &&
    selectedCombinations.value.length === filteredCombinations.value.length
  );
});

const isIndeterminate = computed(() => {
  return (
    selectedCombinations.value.length > 0 &&
    selectedCombinations.value.length < filteredCombinations.value.length
  );
});

// 表格行选择配置
const rowSelection = reactive({
  selectedRowKeys: selectedCombinations,
  onChange: (keys: string[]) => {
    selectedCombinations.value = keys;
  },
});

// 方法
const getCurrentScenarioName = () => {
  const scenario = scenarios.value.find((s) => s.id === selectedScenario.value);
  return scenario ? scenario.name : '';scenarioscenario.namescenarioscenario.name
};

const selectScenario = (scenarioId: string) => {
  selectedScenario.value = scenarioId;
  selectedCombinations.value = [];
};

const handleSelectAll = (checked: boolean) => {
  selectedCombinations.value = checked
    ? filteredCombinations.value.map((item) => item.id)
    : [];checkedfilteredCombinations.value.mapitem.idcheckedfilteredCombinations.value.mapitem.id
};

// 模态框显示函数
const showAddCategoryModal = () => {
  categoryModalVisible.value = true;
};

const showAddCombinationModal = () => {
  currentCombination.value = null;
  combinationModalVisible.value = true;
};

const showAddCommonItemModal = () => {
  commonItemModalVisible.value = true;
};

// 组合操作函数
const editCombination = (combination: any) => {
  currentCombination.value = { ...combination };
  combinationModalVisible.value = true;
};

const viewCombination = (combination: any) => {
  currentCombination.value = { ...combination };
  combinationModalVisible.value = true;
};

const deleteCombination = async (id: string) => {
  try {
    await new Promise((resolve) => setTimeout(resolve, 500));
    combinations.value = combinations.value.filter((c) => c.id !== id);
    message.success('删除成功');
  } catch {
    message.error('删除失败');
  }
};

const handleBatchDelete = async () => {
  if (selectedCombinations.value.length === 0) {
    message.warning('请先选择要删除的组合');
    return;
  }

  try {
    await new Promise((resolve) => setTimeout(resolve, 500));
    const idsToDelete = new Set(selectedCombinations.value);
    combinations.value = combinations.value.filter(
      (c) => !idsToDelete.has(c.id),
    );
    selectedCombinations.value = [];
    message.success('批量删除成功');
  } catch {
    message.error('批量删除失败');
  }
};

// 保存处理函数
const handleCategorySave = (category: any) => {
  if (category.id) {
    // 编辑现有场景
    const index = scenarios.value.findIndex((s) => s.id === category.id);
    if (index !== -1) {
      scenarios.value[index] = { ...category };
    }
  } else {
    // 添加新场景
    category.id = Date.now().toString();
    scenarios.value.push(category);
  }
  message.success('场景保存成功');
  categoryModalVisible.value = false;
};

const handleCombinationSave = (combination: any) => {
  if (combination.id) {
    // 编辑现有组合
    const index = combinations.value.findIndex((c) => c.id === combination.id);
    if (index !== -1) {
      combinations.value[index] = { ...combination };
    }
  } else {
    // 添加新组合
    combination.id = Date.now().toString();
    combination.scenario = selectedScenario.value;
    combination.addedBy = '当前用户';
    combination.addTime = new Date().toLocaleString();
    combinations.value.push(combination);
  }
  message.success('组合保存成功');
  combinationModalVisible.value = false;
};

const handleCommonItemSave = (item: any) => {
  // 处理常用项保存
  message.success('常用项保存成功');
  commonItemModalVisible.value = false;
};

// 页面初始化
onMounted(() => {
  loading.value = false;
});
</script>

<template>
  <div class="combinations-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">自定组合类</h1>
      <p class="page-description">
        (在工作场景中定制化您更喜欢的商品组合分类,工作更加效率)
      </p>
    </div>

    <!-- 全局操作按钮 -->
    <div class="action-bar">
      <div class="left-actions">
        <a-button type="primary" @click="showAddCategoryModal">
          <template #icon><Plus /></template>
          + 添加自定类
        </a-button>
        <a-button @click="showAddCommonItemModal">
          <template #icon><Plus /></template>
          + 添加常用项
        </a-button>
      </div>
      <div class="right-actions">
        <a-button
          danger
          :disabled="selectedCombinations.length === 0"
          @click="handleBatchDelete"
        >
          <template #icon><Trash2 /></template>
          合批量删除
        </a-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧使用场景列表 -->
      <div class="scenarios-sidebar">
        <div class="scenarios-header">
          <h3>使用场景</h3>
        </div>
        <div class="scenarios-list">
          <div
            v-for="scenario in scenarios"
            :key="scenario.id"
            class="scenario-item"
            :class="[{ active: selectedScenario === scenario.id }]"
            @click="selectScenario(scenario.id)"
          >
            {{ scenario.name }}
          </div>
        </div>
      </div>

      <!-- 右侧组合列表 -->
      <div class="combinations-content">
        <div class="combinations-header">
          <div class="header-left">
            <h3>{{ getCurrentScenarioName() }}组合</h3>
            <a-button
              type="primary"
              size="small"
              @click="showAddCombinationModal"
            >
              <template #icon><Plus /></template>
              +添加
            </a-button>
          </div>
          <div class="header-right">
            <a-checkbox
              :checked="isAllSelected"
              :indeterminate="isIndeterminate"
              @change="handleSelectAll"
            >
              全选
            </a-checkbox>
          </div>
        </div>

        <!-- 组合列表表格 -->
        <div class="combinations-table">
          <a-table
            :columns="columns"
            :data-source="filteredCombinations"
            :pagination="false"
            :row-selection="rowSelection"
            :loading="loading"
            size="small"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.key === 'action'">
                <a-space>
                  <a-button
                    type="link"
                    size="small"
                    @click="editCombination(record)"
                  >
                    <template #icon><UserRoundPen /></template>
                    编辑
                  </a-button>
                  <a-button
                    type="link"
                    size="small"
                    @click="viewCombination(record)"
                  >
                    <template #icon><Search /></template>
                    查看
                  </a-button>
                  <a-popconfirm
                    title="确定要删除这个组合吗？"
                    @confirm="deleteCombination(record.id)"
                  >
                    <a-button type="link" size="small" danger>
                      <template #icon><Trash2 /></template>
                      删除
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </template>
          </a-table>
        </div>

        <!-- 提示信息 -->
        <div class="info-text">
          <span class="info-icon">→</span>
          <span class="info-content">
            设置组合后,在该类型服务单中选用组合即可一键套用组合内全部商品
          </span>
        </div>
      </div>
    </div>

    <!-- 模态框组件 -->
    <CategoryModal
      v-model:visible="categoryModalVisible"
      :scenarios="scenarios"
      @save="handleCategorySave"
    />

    <CombinationModal
      v-model:visible="combinationModalVisible"
      :scenario="selectedScenario"
      :combination="currentCombination"
      @save="handleCombinationSave"
    />

    <CommonItemModal
      v-model:visible="commonItemModalVisible"
      :scenario="selectedScenario"
      @save="handleCommonItemSave"
    />
  </div>
</template>

<style scoped>
/* 响应式设计 */
@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }

  .left-actions {
    justify-content: center;
  }

  .main-content {
    flex-direction: column;
  }

  .scenarios-sidebar {
    width: 100%;
    height: 200px;
  }
}

.combinations-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f5f5;
}

.page-header {
  padding: 24px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
}

.page-title {
  margin: 0 0 8px;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.page-description {
  margin: 0;
  font-size: 14px;
  color: #666;
}

.action-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
}

.left-actions {
  display: flex;
  gap: 8px;
}

.main-content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.scenarios-sidebar {
  display: flex;
  flex-direction: column;
  width: 200px;
  background: white;
  border-right: 1px solid #e8e8e8;
}

.scenarios-header {
  padding: 16px;
  border-bottom: 1px solid #e8e8e8;
}

.scenarios-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.scenarios-list {
  flex: 1;
  overflow-y: auto;
}

.scenario-item {
  padding: 12px 16px;
  cursor: pointer;
  border-left: 3px solid transparent;
  transition: all 0.3s;
}

.scenario-item:hover {
  background-color: #f5f5f5;
}

.scenario-item.active {
  color: #1890ff;
  background-color: #e6f7ff;
  border-left-color: #1890ff;
}

.combinations-content {
  display: flex;
  flex: 1;
  flex-direction: column;
  overflow: hidden;
}

.combinations-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
}

.header-left {
  display: flex;
  gap: 16px;
  align-items: center;
}

.header-left h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.combinations-table {
  flex: 1;
  overflow: hidden;
  background: white;
}

.info-text {
  display: flex;
  gap: 8px;
  align-items: center;
  padding: 16px 24px;
  background: white;
  border-top: 1px solid #e8e8e8;
}

.info-icon {
  font-weight: bold;
  color: #ff4d4f;
}

.info-content {
  font-size: 14px;
  color: #666;
}
</style>
